package com.argrace.smart.rokid;

import android.util.Log;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * Created by argrace_dev_1 on 2018/2/25.
 */

public class RokidMulticastRecieverThread implements Runnable {
    private String add = null;

    private int port = 0;
    private RecieveUdpThreadCallBack callBack;
    private boolean is_continue = true;
    MulticastSocket ms;

    public RokidMulticastRecieverThread(String add, int port, RecieveUdpThreadCallBack callBack) {
        this.add = add;
        this.port = port;
        this.callBack = callBack;
    }

    @Override
    public void run() {
        byte[] data = new byte[4096];
        while (is_continue) {
            Log.i("info", "监听:" + add + ":" + port + "中....");
            try {
                InetAddress groupAddress = InetAddress.getByName(add);
                ms = new MulticastSocket(port);
                ms.joinGroup(groupAddress);
                DatagramPacket dp = new DatagramPacket(data, data.length);
                if (ms != null) {
                    ms.receive(dp);
                }
                String quest_ip = dp.getAddress().toString();
                String codeString = new String(dp.getData(), 0, dp.getLength()).trim();
                Log.i("info","监听获取的消息是" + codeString);
                String[] args = codeString.split("\r\n");
                if (args[2] != null && args[2].equals("ST: homebase:device")) {
                    callBack.callBack(args[4]);
                }
            } catch (Exception e) {
            }
        }
        if (ms != null) {
            ms.close();
        }
    }

    public interface RecieveUdpThreadCallBack {
        public void callBack(String msg);
    }
}

